package vic.sendreceive.utilities;

import java.io.UnsupportedEncodingException;

public class Encryption {
	private static String keyRC4 = "ken123";
	private static byte[] sbox = new byte[255];
	private static byte[] mykey = new byte[255];
    @SuppressWarnings("unused")
	private static int[] key = new int[] { 31, 152, 8, 257, 56, 89, 366, 21, 168, 172 };
   public static String encrypt(String src, String key) throws UnsupportedEncodingException { 
		byte[] mtxt =  src.getBytes("ASCII");
		byte[] mkey =  key.getBytes("ASCII");
		byte[] result = calculate(mtxt, mkey);
		return charsToHex(result);
	}

	public static String decrypt(String src, String key) throws UnsupportedEncodingException {
		byte[] mtxt = hexToChars(src);
		byte[] mkey = key.getBytes("ASCII");
		byte[] result = calculate(mtxt, mkey);
		return new String(result, "ASCII");
	}
	
	private static byte[] calculate(byte[] plaintxt, byte[] psw) {
		initialize(psw);
		byte i = 0; 
		byte j = 0; 
		int len = plaintxt.length;
		byte[] cipher = new byte[len];
		int k;
		byte temp, cipherby;		
		for (int a = 0; a < len; a++) {
			i = (byte)((i + 1) % 255);
			j = (byte)((j + sbox[i]) % 255);
			temp = sbox[i];
			sbox[i] = sbox[j];
			sbox[j] = temp;
			byte idx = (byte)((sbox[i] + sbox[j]) % 255);
			k = sbox[idx];
			cipherby = (byte)(plaintxt[a]^k);
			cipher[a] = cipherby;
		}
		return cipher;
	}

	private static void initialize(byte[] pwd) 
	{
		byte b = 0;
		byte tempSwap;
		int intLength = pwd.length;
		
		for (byte a = 0; a < 255; a++) {
			mykey[a] = pwd[(a % intLength)];
			sbox[a] = a;
		}

		for (byte a = 0; a < 255; a++) {
			b = (byte)((b + sbox[a] + mykey[a]) % 255);
			tempSwap = sbox[a];
			sbox[a] = sbox[b];
			sbox[b] = tempSwap;
		}
	}

	private static String charsToHex(byte[] chars) {
		String result = "";
		int len = chars.length;
		for (int i = 0; i < len; i++) {
			result += String.format("{0:x2}", chars[i]);
		}
		return result;			
	}

	private static byte[] hexToChars(String hex) {
		int len = hex.length();
		byte[] codes = new byte[len/2];
		for (int i = (hex.substring(0, 2) == "0x") ? 2 : 0; i < len; i += 2) {
			codes[i/2] = Byte.valueOf(hex.substring(i, 2), 16);
		}
		return codes;
	}
	

    public static String encryptRC4(String src) throws UnsupportedEncodingException {
        return encrypt(src, keyRC4);
    }
    public static String decryptRC4(String src) throws UnsupportedEncodingException {
        return decrypt(src, keyRC4);
    }
    
    
    public static String Encrypt2(String srcStr) {
    	//Base64Encrypt.compressGZip(srcStr);
    	return srcStr;
    	//return Base64Encrypt.Encode(srcStr);    	    
    }
    
    public static String Decrypt2(String srcStr) {
    	return srcStr;
		//return Base64Encrypt.Decode(srcStr);    		       
    }  
    
    
	
}
